package com.zjh.dao.user;

import com.zjh.dao.BaseDao;
import com.zjh.pojo.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl implements UserDao {
    @Override
    public User login(Connection connection, String name) throws SQLException {
        PreparedStatement pst = null;
        ResultSet rs = null;
        User user = null;

        if (connection != null) {
            String sql = "SELECT * FROM test.users where name=?";
            Object[] params = {name};
            rs = BaseDao.execute(connection, rs, pst, sql, params);

            if (rs.next()) {
                user = new User();
                user.setId(rs.getInt("id"));
                user.setName(rs.getString("name"));
                user.setPassword(rs.getString("password"));
                user.setEmail(rs.getString("email"));
                user.setBirthday(rs.getString("birthday"));
            }
            BaseDao.CloseResource(connection, pst, rs);
            System.out.println(user);
        }
        return user;
    }

    @Override
    public int register(Connection connection, User user) throws SQLException {
        PreparedStatement pstm = null;
        int updateNum = 0;
        if (connection != null) {
            String sql = "insert into users (id,name,password," +
                    "email,birthday) " +
                    "values(?,?,?,?,?)";
            Object[] params = {user.getId(), user.getName(), user.getPassword(), user.getEmail(), user.getBirthday()};
            updateNum = BaseDao.execute(connection, pstm, sql, params);
            BaseDao.CloseResource(null, pstm, null);
        }
        return updateNum;
    }
}
